#![allow(non_snake_case)]
use leptos::prelude::*;
use shq_web_controls::{MultiTreeSelect, TreeItems};
use std::vec::Vec;

// 导入服务器函数
use crate::utils::server_functions::{fetch_top_user, get_role_users};

#[component]
pub fn RoleUserComponent(
    // #[prop(optional)]
    sel_role_id: ReadSignal<Option<u32>>,
    selected_user_ids: RwSignal<Vec<String>>,
) -> impl IntoView {
    // 获取员工数据
    let user_items = Resource::new(move || (), |_| async { fetch_top_user().await });
    let role_uers = LocalResource::new(move || {
        let id = sel_role_id.get();
        async move {
            if let Some(role_id) = id {
                get_role_users(role_id).await
            } else {
                Ok(vec![])
            }
        }
    });

    let sel_user_ids = Memo::new(move |_| {
        let sel_user_ids: Vec<String> = role_uers.get().as_deref().cloned()
            .iter()
            .flat_map(|user_id_result| match user_id_result {
                Ok(menu_ids) => menu_ids.iter()
                    .map(|id| {
                        // 处理转义引号，移除多余的引号
                        let s = format!("{:?}", id);
                        s.trim_matches('"').to_string()
                    })
                    .collect::<Vec<String>>(),
                Err(_) => vec![],
            })
            .collect();
        sel_user_ids
    });
    // 用户选择变更处理
    let on_change = move |selected_users: Vec<String>| {
        // 过滤掉以"o_"开头的key，只保留员工ID
        let employee_ids: Vec<String> = selected_users
            .into_iter()
            .filter(|key: &String| !key.starts_with("o_"))
            .collect();

        // // 获取当前的 sel_user_ids
        // let current_sel_user_ids = match role_uers.get() {
        //     Some(Ok(user_ids)) => user_ids
        //         .iter()
        //         .map(|id| {
        //             // 处理转义引号，移除多余的引号
        //             let s = format!("{:?}", id);
        //             s.trim_matches('"').to_string()
        //         })
        //         .collect::<Vec<String>>(),
        //     _ => vec![],
        // };
        // // // 合并 employee_ids 和 current_sel_user_ids，并去重
        // let combined_ids = [&employee_ids[..], &current_sel_user_ids[..]].concat();
        // let unique_ids: Vec<String> = combined_ids
        //     .into_iter()
        //     .collect::<std::collections::HashSet<_>>()
        //     .into_iter()
        //     .collect();
        selected_user_ids.set(employee_ids);
    };
    view! {
        <div class="bg-white shadow rounded-lg p-4 flex-1 flex flex-col min-h-1">
            <h1 class="text-xl font-bold mb-4">用户</h1>
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                {move || match user_items.get() {
                    Some(Ok(user)) => {
                        let user_tree_items = StoredValue::new(TreeItems::from(&user));
                        view! {
                            <div class="flex-1 overflow-y-auto min-h-1">
                                <MultiTreeSelect
                                    tree_items=user_tree_items
                                    show_confirm_cancel_btn=false
                                    on_change
                                    values=sel_user_ids.get()
                                />
                            </div>
                        }.into_any()
                    }
                    Some(Err(e)) => {
                        let error_message = e.to_string();
                        view! {
                            <div class="p-4 text-red-500">
                                {error_message}
                            </div>
                        }.into_any()
                    }
                    None => {
                        view! {
                            <div class="flex-1 flex items-center justify-center">
                                "正在加载数据..."
                            </div>
                        }.into_any()
                    }
                }}
            </Suspense>
        </div>
    }
    .into_any()
}
